package com.example.dangdangbackend.service.impl;

import com.example.dangdangbackend.DTO.AddAddressDTO;
import com.example.dangdangbackend.VO.AddressDetailVO;
import com.example.dangdangbackend.common.BaseContext;
import com.example.dangdangbackend.entity.Address;
import com.example.dangdangbackend.mapper.AddressMapper;
import com.example.dangdangbackend.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void addAddressService(AddAddressDTO addAddressDTO) {
        int userId = BaseContext.getCurrentId();
        Address address = new Address();
        address.setCity(addAddressDTO.getCity());
        address.setName(addAddressDTO.getName());
        address.setMobile(addAddressDTO.getMobile());
        address.setDetail(addAddressDTO.getDetail());
        address.setDistrict(addAddressDTO.getDistrict());
        address.setTown(addAddressDTO.getTown());
        address.setProvince(addAddressDTO.getProvince());
        address.setUserId(userId);
        String currentTimeString = LocalDateTime.now().format(formatter);
        LocalDateTime time = LocalDateTime.parse(currentTimeString, formatter);
        address.setCreateTime(time);
        address.setUpdateTime(time);

        addressMapper.insertIntoAddress(address);
    }

    @Override
    public List<AddressDetailVO> selectAddressDetail() {
        int userId = BaseContext.getCurrentId();

        return addressMapper.selectAddressDetail(userId);

    }

    @Override
    public void deleteAddress(int addressId) {
        addressMapper.deleteAddress(addressId);
    }

    @Override
    public void updateAddress(Address address) {
        String currentTimeString = LocalDateTime.now().format(formatter);
        LocalDateTime time = LocalDateTime.parse(currentTimeString, formatter);
        address.setUpdateTime(time);

        addressMapper.updateAddress(address);
    }


}
